import React from 'react';
import { Card, Form, Input, DatePicker, Select, Button, Space, Table, Modal, message, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';

const { RangePicker } = DatePicker;
const { Option } = Select;

const COUNTRY_SET = [
  { value: 'CN', label: '中国' },
  { value: 'US', label: '美国' },
  { value: 'DE', label: '德国' },
  { value: 'JP', label: '日本' },
];

export default function IDardList() {
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [loading, setLoading] = React.useState(false);
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [current, setCurrent] = React.useState(null);
  const [list, setList] = React.useState(() => {
    const saved = localStorage.getItem('idard-list');
    if (saved) return JSON.parse(saved);
    return Array.from({ length: 12 }).map((_, i) => ({
      id: i + 1,
      name: `证件-${i + 1}`,
      type: i % 2 === 0 ? '身份证' : '护照',
      country: COUNTRY_SET[i % COUNTRY_SET.length].value,
      year: 2000 + (i % 20),
      month: (i % 12) + 1,
      day: (i % 28) + 1,
      content: '示例证件信息',
      createTime: new Date(Date.now() - i * 86400000).toLocaleString(),
    }));
  });
  const [filtered, setFiltered] = React.useState(list);

  React.useEffect(() => {
    localStorage.setItem('idard-list', JSON.stringify(list));
    setFiltered(list);
  }, [list]);

  const handleSearch = () => {
    const { name, type, dateRange } = form.getFieldsValue();
    const res = list.filter((x) => {
      const m1 = name ? x.name.toLowerCase().includes(name.toLowerCase()) : true;
      const m2 = type ? x.type === type : true;
      let m3 = true;
      if (dateRange && dateRange.length === 2) {
        const [start, end] = dateRange;
        const st = start.startOf('day').valueOf();
        const ed = end.endOf('day').valueOf();
        const ct = new Date(x.createTime).valueOf();
        m3 = ct >= st && ct <= ed;
      }
      return m1 && m2 && m3;
    });
    setFiltered(res);
  };

  const onReset = () => {
    form.resetFields();
    setFiltered(list);
  };

  const openDialog = (record) => {
    setCurrent(record || null);
    setDialogOpen(true);
    if (record) {
      editForm.setFieldsValue({ ...record });
    } else {
      editForm.resetFields();
      editForm.setFieldsValue({ type: '身份证', country: 'CN', year: 2024, month: 1, day: 1 });
    }
  };

  const saveIDard = async () => {
    try {
      const values = await editForm.validateFields();
      setList((prev) => {
        if (!current) {
          const id = Date.now();
          return [{ id, createTime: new Date().toLocaleString(), ...values }, ...prev];
        }
        return prev.map((x) => (x.id === current.id ? { ...x, ...values } : x));
      });
      setDialogOpen(false);
      message.success('证件信息已保存（本地模拟）');
    } catch (e) {}
  };

  const delIDard = (record) => {
    Modal.confirm({
      title: '删除确认',
      content: `确定删除证件 ${record.name} 吗？`,
      onOk: () => {
        setList((prev) => prev.filter((x) => x.id !== record.id));
        message.success('已删除该证件');
      },
    });
  };

  const columns = [
    { title: '名称', dataIndex: 'name', key: 'name', align: 'center' },
    { title: '证件信息', dataIndex: 'content', key: 'content', align: 'center' },
    { title: '类型', dataIndex: 'type', key: 'type', width: 230, align: 'center', render: (v) => <Tag color="blue">{v}</Tag> },
    { title: '年份', dataIndex: 'year', key: 'year', width: 100, align: 'center' },
    { title: '月份', dataIndex: 'month', key: 'month', width: 100, align: 'center' },
    { title: '日期', dataIndex: 'day', key: 'day', width: 100, align: 'center' },
    { title: '录入时间', dataIndex: 'createTime', key: 'createTime', width: 160, align: 'center' },
    { title: '操作', key: 'actions', width: 160, align: 'center', fixed: 'right', render: (_, record) => (
      <Space size="small">
        <Button size="small" type="primary" icon={<EditOutlined />} onClick={() => openDialog(record)}>编辑</Button>
        <Button size="small" danger icon={<DeleteOutlined />} onClick={() => delIDard(record)}>删除</Button>
      </Space>
    ) },
  ];

  return (
    <div className="idard" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Card title="证件列表" variant="outlined">
        <Form form={form} layout="inline" onFinish={handleSearch} style={{ rowGap: 12 }}>
          <Form.Item label="名称" name="name"><Input allowClear placeholder="请输入名称关键词" style={{ width: 220 }} /></Form.Item>
          <Form.Item label="类型" name="type">
            <Select allowClear placeholder="请选择类型" style={{ width: 180 }}>
              <Option value="身份证">身份证</Option>
              <Option value="护照">护照</Option>
              <Option value="驾照">驾照</Option>
            </Select>
          </Form.Item>
          <Form.Item label="时间范围" name="dateRange"><RangePicker /></Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button onClick={onReset}>重置</Button>
              <Button type="primary" icon={<PlusOutlined />} onClick={() => openDialog(null)}>新增</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`证件记录（共 ${filtered.length} 条）`} variant="outlined">
        <Table
          rowKey="id"
          dataSource={filtered}
          loading={loading}
          columns={columns}
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1200 }}
        />
      </Card>

      <Modal open={dialogOpen} title={current ? '编辑证件' : '新增证件'} okText="保存" cancelText="取消" onOk={saveIDard} onCancel={() => setDialogOpen(false)}>
        <Form form={editForm} layout="vertical">
          <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
            <Input placeholder="例如：张三身份证" />
          </Form.Item>
          <Form.Item label="类型" name="type" rules={[{ required: true, message: '请选择类型' }]}>
            <Select>
              <Option value="身份证">身份证</Option>
              <Option value="护照">护照</Option>
              <Option value="驾照">驾照</Option>
            </Select>
          </Form.Item>
          <Form.Item label="国家/地区" name="country" rules={[{ required: true, message: '请选择国家/地区' }]}>
            <Select>
              {COUNTRY_SET.map((c) => <Option key={c.value} value={c.value}>{c.label}</Option>)}
            </Select>
          </Form.Item>
          <Form.Item label="年份" name="year" rules={[{ required: true, message: '请输入年份' }]}>
            <Input type="number" min={1900} />
          </Form.Item>
          <Form.Item label="月份" name="month" rules={[{ required: true, message: '请输入月份' }]}>
            <Input type="number" min={1} max={12} />
          </Form.Item>
          <Form.Item label="日期" name="day" rules={[{ required: true, message: '请输入日期' }]}>
            <Input type="number" min={1} max={31} />
          </Form.Item>
          <Form.Item label="证件信息" name="content">
            <Input.TextArea rows={4} placeholder="例如：身份证号/护照号等信息" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}